const fs = require('fs');
const nodeUtil = require('util');

const express = require('express');
const router = express.Router();
const rp = require('request-promise-native');
const log4js = require('log4js');


const mkdir = nodeUtil.promisify(fs.mkdir);

/**
 * 创建目录，并返回路径地址，args为目录层级数组
 */
const mkdirs = (path, args)=>{
  if (! fs.existsSync(path)){
    fs.mkdirSync(path);
  }
  if (args && args.length){
    let dir = args.shift();
    return mkdirs(`${path}/${dir}`, args);
  }else{
    return path;
  }
};

mkdirs('./logs');    //日志目录

// 日志
log4js.configure({
      appenders : [
         {type : 'console'},
         {
            type : 'file',
            filename : 'logs/access.log' ,
            maxLogSize : 10240000,
            backups : 30,
            category : 'access'
         },
         {
            type: 'file',
            filename : 'logs/wx.log' ,
            maxLogSize : 10240000,
            backups : 30,
            category : 'wx'
         }
      ],
      replaceConsole: true
   });
const logger = log4js.getLogger('wx');
logger.setLevel('DEBUG');

let accessToken = '';

/* GET home page. */
router.get('/', function(req, res, next) {
  res.end(accessToken);
});

const getAccessToken = async ()=>{
  let options = {
    method: 'GET',
    uri: 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxb4daebad3b5b504f&secret=06b5e790da6e43c3f46b1b27c045a896',
    json: true
  };
  try{
    let res = await rp(options);
    logger.debug('request access token : ', res);
    accessToken = res.access_token;
    setTimeout(getAccessToken, res.expires_in * 1000);
  }catch(e){
    console.log('error ------> ', e);
  }
}

getAccessToken();

module.exports = router;
